import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import styles from '../css/suborder.module.css';
import left from '../assets/left.png';
import hourse3 from '../assets/hourse3.png';
import { Toast } from 'antd-mobile'; // 引入 Toast 组件


const SubOrder = () => {
    const navigate = useNavigate();
    const [showAlert, setShowAlert] = useState(false);
    const [selectedDate, setSelectedDate] = useState(null);
    const [quantity, setQuantity] = useState(1);
    const [dates, setDates] = useState([]);
    const [dateWarning, setDateWarning] = useState(false);
    const [userInfo, setUserInfo] = useState({
        nickname: '',
        tel: '',
        code: ''
    });
    const [ticketInfo, setTicketInfo] = useState({
        name: '',
        current_price: 0,
        id: ''
    });

    // 从sessionStorage获取数据
    // 在 useEffect 中正确调用
    useEffect(() => {
        const nickname = sessionStorage.getItem("nickname");
        const tel = sessionStorage.getItem("tel");
        const code = sessionStorage.getItem("code") || "暂无身份证号";
        const deata = JSON.parse(sessionStorage.getItem('reservedTicket'));
        const unitPrice = sessionStorage.getItem("unitPrice");
        const numding = sessionStorage.getItem("numding");
        const numstate = sessionStorage.getItem("numstate");

        setUserInfo({ nickname, tel, code });

        if (deata) {
            const price = deata.current_price || unitPrice;
            setTicketInfo({
                name: deata.name,
                current_price: price,
                id: deata.id
            });
            generateDates(price); // 确保使用正确的价格生成日期
        } else {
            generateDates(0); // 如果没有数据，使用0作为默认价格
        }

        // 设置初始数量
        if (numstate === "true") {
            setQuantity(1);
        } else if (numstate === "false" && numding) {
            setQuantity(parseInt(numding));
        }
    }, []);

    // 生成日期列表 - 修改为接收价格参数
    const generateDates = (price = 0) => {
        const startDate = new Date();
        const endDate = new Date(startDate);
        endDate.setDate(endDate.getDate() + 7);
        const dateList = [];

        let currentDate = new Date(startDate);
        while (currentDate <= endDate) {
            const dateStr = currentDate.toISOString().split('T')[0];
            dateList.push({
                date: dateStr,
                price: price,
                isToday: dateStr === startDate.toISOString().split('T')[0] // 添加 isToday 字段
            });
            currentDate.setDate(currentDate.getDate() + 1);
        }

        setDates(dateList);
    };
    // 返回上一页
    const handleBack = () => {
        navigate(-1);
    };

    // 跳转首页
    const handleHome = () => {
        navigate("/home");
    };

    // 显示购买须知
    const handleShowAlert = () => {
        setShowAlert(true);
    };

    // 关闭购买须知
    const handleCloseAlert = () => {
        setShowAlert(false);
    };

    // 选择日期
    const handleSelectDate = (date) => {
        setSelectedDate(date);
    };

    // 显示更多日期选择器
    const handleShowMoreDates = () => {
        const datePicker = document.getElementById('datePicker');
        if (datePicker) {
            datePicker.scrollBy({ left: 200, behavior: 'smooth' }); // 向右滑动200px
        }
    };

    // 增加数量
    const handleIncrease = () => {
        setQuantity(prev => prev + 1);
    };

    // 减少数量
    const handleDecrease = () => {
        if (quantity > 1) {
            setQuantity(prev => prev - 1);
        }
    };

    // 提交订单
    const handleSubmitOrder = async () => {
        if (!selectedDate) {
            setDateWarning(true); // 激活警告样式
            setTimeout(() => setDateWarning(false), 2000); // 2秒后恢复
            return;
        }

        const totalPrice = quantity * ticketInfo.current_price;

        if (totalPrice === 0) {
            Toast.show({
                content: '总价不能为0',
                position: 'top',
                duration: 2000
            });
            return;
        }

        const scenic_id = sessionStorage.getItem("jingid");
        const userid = sessionStorage.getItem("userid");

        const orderData = {
            scenic_id,
            ticketing_id: ticketInfo.id,
            number: quantity,
            total_price: totalPrice,
            user_id: userid,
            time: selectedDate,
            status: 2
        };

        // 存储订单信息
        sessionStorage.setItem("allPrice", totalPrice);
        sessionStorage.setItem("shopData", JSON.stringify(orderData));

        // 打印订单信息
        console.log("订单数据:", orderData);

        // 跳转到支付页面
        navigate("/buypay");
    };

    // 计算总价
    const totalPrice = quantity * ticketInfo.current_price;
    // 可以添加这个样式常量
    const buttonStyle = {
        width: '30px',
        height: '30px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        border: '1px solid #ddd',
        borderRadius: '4px',
        cursor: 'pointer',
        userSelect: 'none'
    };
    return (
        <div className={styles.container}>
            {/* 购买须知弹窗 */}
            {showAlert && (
                <div className={styles.alert}>
                    <div className={styles.alertOne}>
                        <div className={styles.close} onClick={handleCloseAlert}>
                            关闭
                        </div>
                    </div>
                </div>
            )}

            {/* 顶部导航 */}
            <div className={styles.top}>
                <div style={{ display: 'flex', alignItems: 'center', whiteSpace: 'nowrap', width: '50%', justifyContent: 'space-between' }}>
                    <div className={styles.left}>
                        <img src={left} alt="" onClick={handleBack} />
                        <div className={styles.line}></div>
                        <img id="hourse" src={hourse3} alt="" onClick={handleHome} />
                    </div>
                </div>
                <p style={{ marginLeft: '-3%' }}>提交订单</p>
            </div>

            {/* 门票标题 */}
            <h3 className={styles.hthree}>{ticketInfo.name}</h3>

            {/* 选择日期 */}
            <div className={styles.date}>
                <div className={styles.optionDate}>
                    <h3>选择日期</h3>
                    <p style={dateWarning? {
                        fontSize: '18px',
                        fontWeight: 'bold',
                        color: '#e55b5b',
                        transition: 'all 0.3s ease' // 添加平滑过渡效果
                    } : { color: '#e55b5b' }}>
                        请先选择使用日期 !
                    </p>
                </div>
                <div className={styles.block}>
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <div className={styles.datePicker} id="datePicker">
                            {dates.map((item, index) => (
                                <div
                                    key={index}
                                    className={`${styles.dateItem} ${selectedDate === item.date? styles.selected : ''}`}
                                    onClick={() => handleSelectDate(item.date)}
                                    style={{ marginLeft: item.isToday? '410px' : '5px' }} // 根据 isToday 设置 marginLeft
                                >
                                    <p className={styles.dateP}>{item.date}</p>
                                    <span className={styles.dateSpan}>￥{item.price}</span>
                                </div>
                            ))}
                        </div>
                        <div className={styles.blockTwo} onClick={handleShowMoreDates}>
                            <div className={styles.orange}>￥{ticketInfo.current_price}起</div>
                            <div>
                                <div style={{ width: '40px', height: '18px', fontSize: '14px', margin: '0 2px', marginLeft: '17px' }}>更多</div>
                                <div style={{ width: '40px', height: '18px', fontSize: '14px', margin: '0 2px', marginLeft: '17px' }}>日期</div>
                            </div>
                            {/* <img src={rightArrow} alt="" /> */}
                        </div>
                    </div>
                </div>
                <div className={styles.bot}>
                    <span>无序退票 | 随时退 |</span>
                    <span style={{ color: '#e55b5b' }}>需携带游客身份证</span>
                    <div style={{ display: 'flex', alignItems: 'center' }} onClick={handleShowAlert}>
                        <span>购买须知</span>
                        {/* <img src={rightArrow} alt="" /> */}
                    </div>
                </div>
            </div>

            {/* 选择数量 */}
            <div className={styles.number}>
                <div className={styles.num}>
                    <h3>选择数量</h3>
                    <div className={styles.pedometer}>
                        <div onClick={handleDecrease} style={buttonStyle}>
                            -
                        </div>
                        <input
                            type="number"
                            className={styles.shopnums}
                            value={quantity}
                            onChange={(e) => setQuantity(Number(e.target.value))}
                            min="1"
                            style={{
                                width: '40px',
                                height: '30px',
                                textAlign: 'center',
                                margin: '0 5px',
                                border: '1px solid #ddd',
                                borderRadius: '4px'
                            }}
                        />
                        <div onClick={handleIncrease} style={buttonStyle}>
                            +
                        </div>
                    </div>
                </div>
                <div className={styles.astrict}>
                    <span>每单限购1张，同一证件当天限购一张</span>
                </div>
                <div className={styles.tourist}>
                    <h3>游客信息</h3>
                    <div className={styles.disFont}>
                        <div className={styles.font}><span>姓名：</span></div>
                        <p>{userInfo.nickname}</p>
                    </div>
                    <div className={styles.disFont}>
                        <div className={styles.font}><span>身份证号：</span></div>
                        <p id="idNum">暂无数据</p>
                    </div>
                    <div className={styles.disFont}>
                        <div className={styles.font}><span>手机号：</span></div>
                        <p id="tel">{userInfo.tel}</p>
                    </div>
                </div>
            </div>

            {/* 提交订单 */}
            <div className={styles.bottom}>
                <div style={{ display: 'flex', color: '#e55b5b', alignItems: 'center', marginLeft: '10px' }}>
                    <span id="allNum" style={{ fontSize: '12px' }}>总价</span>&nbsp;
                    <span style={{ fontSize: '10px', color: '#d43079' }}>￥</span>&nbsp;
                    <p style={{ fontSize: '17px', color: '#d43079' }} id="eight">{totalPrice}</p>
                </div>
                <div className={styles.subOrder} onClick={handleSubmitOrder}>
                    提交订单
                </div>
            </div>
        </div>
    );
};

export default SubOrder;